const urlParams = new URLSearchParams(window.location.search);
const oldUsername = urlParams.get('username');
const MAX_LENGTH = 50;
async function fetchUserInfo() {
    const response = await fetch(`/user-info?username=${escapeHTML(oldUsername)}`);
    const data = await response.json();
    document.getElementById('username').value = data.username;
    document.getElementById('name').value = data.name || '';
    document.getElementById('student_id').value = data.student_id || '';
    document.getElementById('role').value = data.role || '学生';
    document.getElementById('email').value = data.email || '';
}

async function saveProfile() {
    const newUsername = document.getElementById('username').value;
    const name = document.getElementById('name').value;
    const student_id = document.getElementById('student_id').value;
    const usernameData = await fetch(`/check-username?username=${escapeHTML(newUsername)}`);
    const usernameExists = await usernameData.json();
    const usernameRegex = /^[a-zA-Z0-9]{3,10}$/;

    if(!newUsername||!name||!student_id){
        alert('请填写所有必填项');
        return;
    }
    if(newUsername.length>MAX_LENGTH||name.length>MAX_LENGTH){
        alert('用户名或姓名长度不能超过50个字符');
        return;
    }
    if (!usernameRegex.test(newUsername)) {
        alert('用户名不符合条件');
        return;
    }

    if (usernameExists.exists && newUsername!==oldUsername) {
        alert('用户名已存在，请重新输入');
        return;
    }

    const response = await fetch('/update-user-info', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ oldUsername, newUsername, name, student_id })
    });
    const data = await response.json();
    alert(data.message);
    if (data.message === '信息保存成功') {
        // 若用户名修改成功，更新后续页面跳转使用的用户名
        window.location.href = `success.html?username=${escapeHTML(newUsername)}`;
    }
}

function openChangePasswordModal() {
    document.getElementById('changePasswordModal').style.display = 'flex';
}

function closeChangePasswordModal() {
    document.getElementById('changePasswordModal').style.display = 'none';
}

async function changePassword() {
    const oldPassword = document.getElementById('oldPassword').value;
    const newPassword = document.getElementById('newPassword').value;

    const response = await fetch('/change-password', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username: oldUsername, oldPassword, newPassword })
    });
    const data = await response.json();
    alert(data.message);
    if (data.message === '密码修改成功') {
        closeChangePasswordModal();
    }
}

function goBack() {
    window.location.href = `success.html?username=${escapeHTML(oldUsername)}`;
}

function handleError(data, response) {
    if (response.status === 401 && data.message === '用户未登录') {
        window.location.href = 'login.html';
    }
    throw new Error(data.message);
}


// 示例：在获取用户信息时使用错误处理函数
document.addEventListener('DOMContentLoaded', async () => {
    try {
        const response = await fetch('/user-info');
        const data = await response.json(); // 提前读取响应体
        if (!response.ok) {
            handleError(data, response);
        }
        // 处理用户信息
        const usernameInput = document.getElementById('username');
        const nameInput = document.getElementById('name');
        const studentIdInput = document.getElementById('student_id');

        usernameInput.value = data.username;
        nameInput.value = data.name;
        studentIdInput.value = data.student_id;
    } catch (error) {
        console.error('获取用户信息失败:', error);
    }
});
fetchUserInfo();

// 心跳间隔时间（毫秒）
const HEARTBEAT_INTERVAL = 5000; 

// 心跳机制
function heartbeat() {
    setInterval(async () => {
        try {
            const urlParams = new URLSearchParams(window.location.search);
            const username = urlParams.get('username');
            if (!username) {
                window.location.href = 'login.html';
                return;
            }
            const response = await fetch('/heartbeat', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            const data = await response.json();
            if (data.message!== '心跳正常') {
                window.location.href = 'login.html';
            }
        } catch (error) {
            console.error('心跳请求出错:', error);
            window.location.href = 'login.html';
        }
    }, HEARTBEAT_INTERVAL);
}

// 页面加载时启动心跳机制
window.addEventListener('load', heartbeat);

document.addEventListener('DOMContentLoaded', function() {
    // 获取"返回"链接元素
    const backLink = document.querySelector('ul.flex li:first-child a');
    if (backLink) {
        // 添加点击事件监听器
        backLink.addEventListener('click', function(event) {
            event.preventDefault(); 
            window.location.href = 'success.html'+window.location.search;
        });
    }
});

function escapeHTML(str) {
    return str.replace(/[&<>"']/g, function (match) {
    switch (match) {
    case '&':
    return '&amp;';
    case '<':
    return '&lt;';
    case '>':
    return '&gt;';
    case '"':
    return '&quot;';
    case "'":
    return '&#039;';
}
 });
}